package com.ztsoft.user.controller.dynamic;

import com.google.gson.Gson;
import com.ztsoft.user.common.base.NewBaseController;
import com.ztsoft.user.common.exception.CustomException;
import com.ztsoft.user.pojo.entity.dynamic.DynamicConfig;
import com.ztsoft.user.pojo.enums.ResultCode;
import com.ztsoft.user.service.dynamic.DynamicConfigService;
import com.ztsoft.user.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/dynamicConfig")
@RestController
@Api(tags = "动态配置模块")
@CrossOrigin("*")
public class DynamicConfigController extends NewBaseController<DynamicConfig, String, DynamicConfigService> {

    @Override
    public Result save(@RequestBody DynamicConfig dynamicConfig) {
        String contents = dynamicConfig.getContents();
        try {
            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<>();
            map = gson.fromJson(contents, map.getClass());
            return baseService.saveDynamicConfig(dynamicConfig);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.FAILED.getMsg(), ResultCode.FAILED.getCode());
        }
    }

    @PostMapping("/saveConfig")
    @ApiOperation(value = "保存配置")
    public Result saveConfig(String tableCode, @RequestBody Map<String, Map<String, Object>> map) {
        return baseService.saveConfig(tableCode, map);
    }

    @GetMapping("/queryConfigByTableCode/{tableCode}")
    @ApiOperation(value = "复现配置")
    public Result queryConfigByTableCode(@PathVariable("tableCode") String tableCode) {
        Map<String, Map<String, Object>> map = baseService.queryConfigByTableCode(tableCode);
        return Result.returnDataMsg(ResultCode.SUCCESS.getMsg(), ResultCode.SUCCESS.getCode(), map);
    }
}
